package com.hangsu.train.common.utils;

import org.apache.commons.codec.binary.Hex;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;

public class Digests {

    private static final String SHA1 = "SHA-1";
    private static final String MD5 = "MD5";


    public static byte[] md5(byte[] input, byte[] salt) {
        return digest(input, MD5, salt, 1);
    }

    /**
     * 对字符串进行散列, 支持md5与sha1算法.
     */
    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            if (salt != null) {
                digest.update(salt);
            }

            byte[] result = digest.digest(input);

            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String password = "wlza1d3r4gd3@%";
        String salt = "5124";
        String passwordHex = Hex.encodeHexString(Digests.md5(password.getBytes(), null));
        System.out.println(passwordHex);
    }

}